iT邦幫忙

2024 iThome 鐵人賽

DAY 4
0
Python

初學者的 30 天 Python 復健課程系列 第 4

復健第四天:字串 Strings

  • 分享至 

  • xImage
  •  

Python 之禪

許多自學 Python 的新手們,在各類型的教學影片中可能不常看到這個彩蛋,當我們進入 Python Interactive Shell 後輸入 import this,終端機上會顯示一首由 Tim Peters 所創作的 The Zen of Python 詩詞。

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

這 19 條詩詞是 Python 開發者 Tim Peters 留給 Python 使用者們的建議與指引,其中謠傳說本來留了第 20 條給另外一位 Python 的主要開發者——Guido van Rossum,然而這第 20 條似乎從未被公布,也有可能從一開始就不存在。

維基百科上有中文版本的註釋,不過我個人覺得有些體悟與精華,無法透由翻譯傳達箇中的深奧,只能透過瞭解原文與持續地使用 Python 才能逐漸意會。

其中有一句比較有趣的是——「Although that way may not be obvious at first unless you're Dutch.(儘管這方法一開始並非如此直觀,除非你是荷蘭人。)」,突如其來的「荷蘭人」讓人摸不著頭緒,難不成荷蘭人比較聰明?實際上,這句話中荷蘭人指的是稍早說的另一位 Python 開發者——出生於荷蘭的 Guido van Rossum。

(如果在 Google 搜尋 Tim Peters,會找到一個帥哥)
https://ithelp.ithome.com.tw/upload/images/20240918/20167668KqulJiozMM.png

(但實際上,右邊那個才是工程師 Tim Peters,絕對沒有貼標籤喔!)
https://ithelp.ithome.com.tw/upload/images/20240918/20167668Aa6P9B2d0l.png

什麼是字串 strings?

這個問題看似玄妙,不過在 Python 中,只要任何字元放在兩個單引號('this is a string')或是兩個雙引號("this is also a string"),就會被當作是字串。

如果我們想要輸入多行的文字字串,也可以使用六個(前面三個、後面三的)單引號或是雙引號包覆這些文字,Python 一樣也會將這些字元視為字串,而不受到換行影響。

multiline_string = '''I am a teacher and enjoy teaching.
I didn't find anything as rewarding as empowering people.
That is why I created 30 days of python.'''
print(multiline_string)

如何連接(concatenate)兩個字串?

假設今天我們有兩個字串,如果我們要把這兩個字串連接起來變成一個完整的新字串,這樣的動作在英文稱作——concatenate (使連接),這個英文動詞非常重要,值得佔各位腦中一個記憶體的位置。

要達成 concatenate 也非常簡單,只需要在兩個字串中使用「加號 +」,便可以輕鬆地連接兩個字串,不過要注意的是,在 Python 中,空格(whitespace)也算是一個字元,Python 可不會好心地(隨便地)幫我們自己加上空格。

first_name = "Kobe"
last_name = "Bryant"

print(first_name + last_name) # KobeBryant,中間少了空格
print(first_name + ' ' + last_name) # Kobe Bryant,這樣才是我們想要的結果

如何使用跳脫字元 escape sequence?

對於 Python 初學者來說,單講跳脫字元 escape sequence 可能太過生澀,所以我們換個說法:「如果我們要在兩個單引號之中,再加入單引號 ',應該怎麼做?」

如果我們在 Python 中輸入 sentence = 'I'm a boy.',此時 Python 會顯示 SyntaxError: invalid syntax. Perhaps you forgot a comma?,因為 Python 無法得知我們的字串到底結束在哪裡,因此產生錯誤。

這時候便可以使用反斜線 backslash \ 進行字元跳脫,讓 Python 知道我們希望將特定的單引號 ' 視為一般的字元。

sentence = 'I\'m a boy.'
print(sentence) # I'm a boy.

# 反斜線不會被印出來

如何進行字串格式化 string formatting?

所謂字串格式化 string format,指的是將我們的字串轉換成特定的格式,例如:我們可以在字串中使用 %s,告訴 Python 我們在特定的位置放入對應的變數 variable,這樣講可能蠻令人困惑,所以我們直接透過範例來理解。

first_name = "Charlie"
last_name = "Brown"
pet = "Snoppy"

formatted_string = 'I am %s %s. %s is my pet.' %(first_name, last_name, pet)

print(formatted_string) # I am Charile Brown. Snoppy is my pet.

formatted_string = 'I am %s %s. %s is my pet.' %(pet, last_name, first_name)

print(formatted_string) # I am Snoppy Brown. Charlie is my pet.

發現了嗎?由於字串中有三個 %s,所以 first_namelast_namepet 這三個變數會「依序」被填入。注意我特別強調「依序」這兩個字,因為如果改變變數的順序,會改變進行格式化的字串結果。

除了 %s,我們也可使用 %d 放入整數,用 %f 放入浮點數,甚至可以用 %.2f 指定浮點數要「取到小數點後第二位」

radius = 10
pi = 3.14
area = pi * radius ** 2
formatted_string = 'The area of circle with a radius %d is %.2f.' %(radius, area)

print(formatted_string) # The area of circle with a radius 10 is 314.00.

在 Python 3 中,引入了另一種更直覺的格式化字串的方法——{}.format

first_name = 'Eddie'
last_name = 'Kao'
language = 'Python'
formatted_string = 'I am {} {}. I teach {}'.format(first_name, last_name, language)

print(formatted_string) # I am Eddie Kao. I teach Python.

乍看之下,{} 只取代了 %s,但實際上 %d%f 都可以改用 {} 達到字串格式化,再也不用寄這麼多不同的語法了。

a = 4
b = 3

print('{} * {} = {}'.format(a, b, a * b)) # 4 * 3 = 12
print('{} / {} = {:.2f}'.format(a, b, a / b)) # 4 / 3 = 1.33

工程師真的很懶惰的一種生物,如果說剛剛 {} 已經很方便了,在 Python 3.6 之後又再引入了一個更更更方便的字串插值 string interpolation,又或者稱作 f-Strings

有多方便呢?讓我們直接看範例吧!

a = 4
b = 3
print(f'{a} + {b} = {a + b}') # 4 + 3 = 7

透過在字串前面加上 f,可以在字串中的 {} 進行 Python 運算,然後經由 f 將所有字元轉為字串。

後記

本來這一篇還要囊括字串的切片(slicing)與字串的相關方法(method),沒想到篇幅會變得如此驚人,思量之下還是決定拆成兩篇。

另外大家可能有發現,隨著文章愈加深入,出現的英文詞彙也越來越多,雖然都可以硬翻成中文,不過個人還是會建議瞭解並記憶英文的名詞,對於學習 Python 或是其他程式語言會更有幫助,因為中文的釋義無法完全傳達英文詞彙的原意,也可能因為翻譯的名詞不同,造成初學者上在學習上的混淆。

順邊偷渡一下,我今天在 Medium 發了一篇冷知識文章——為什麼 Git 叫 Git?,有空也可以看一下!


上一篇
復健第三天:布林值 Boolean 與運算子 Operators
下一篇
復健第五天:怎麼還是字串 Strings
系列文
初學者的 30 天 Python 復健課程13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言